<?php

/**
 * admin actions.
 *
 * @package    sf_sandbox
 * @subpackage admin
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class adminActions extends sfActions
{
    /**
     * Executes index action
     *
     */
    public function executeIndex()
    {
    }

    public function executeDashboard()
    {
    }

    public function executeUserList()
    {
    }

    public function executeAp()
    {
        $apService = new ApService();
        $apService->constructAp();

        echo "SUCCESS";
        return sfView::HEADER_ONLY;
    }

    public function executeDoSaveUser()
    {
        $userId = $this->getRequestParameter('userId');
        $userName = $this->getRequestParameter('userName');
        $userPassword = $this->getRequestParameter('userPassword');
        $status = $this->getRequestParameter('status');
        $role = $this->getRequestParameter('role');

        $c = new Criteria();
        $c->add(TblUserPeer::F_USERNAME, $userName);
        if (isset($userId) && trim($userId) != '') {
            $c->add(TblUserPeer::F_ID, $userId, Criteria::NOT_EQUAL);
        }

        $exist = TblUserPeer::doSelectOne($c);
        if ($exist) {
            $output = array(
                "error" => true,
                "errorMsg" => "Username already exist."
            );
            echo json_encode($output);
            return sfView::HEADER_ONLY;
        }

        if (isset($userId) && trim($userId) != '') {
            $tbl_user = TblUserPeer::retrieveByPk($userId);
            if (!isset($tbl_user)) {
                $output = array(
                    "error" => true,
                    "errorMsg" => "Serious Problem happen in server."
                );
                echo json_encode($output);
                return sfView::HEADER_ONLY;
            }

            $c = new Criteria();
            $c->add(TblAdminPeer::F_USER_ID, $userId);
            $tbl_admin = TblAdminPeer::doSelectOne($c);
            if (!isset($tbl_user)) {
                $output = array(
                    "error" => true,
                    "errorMsg" => "Serious Problem happen in server."
                );
                echo json_encode($output);
                return sfView::HEADER_ONLY;
            }
        } else {
            $tbl_admin = new TblAdmin();
            $tbl_user = new TblUser();
        }
        $datetime = date("Y/m/d h:i:s A");

        $tbl_user->setFUsername($userName);
        $tbl_user->setFKeepPassword($userPassword);
        $tbl_user->setFPassword($userPassword);
        $tbl_user->setFKeepPassword2($userPassword);
        $tbl_user->setFPassword2($userPassword);
        $tbl_user->setFType(Globals::USERTYPE_ADMIN);
        $tbl_user->setFStatus($status);
        $tbl_user->save();

        $userId = $tbl_user->getFId();

        $tbl_admin->setFCode($userName);
        $tbl_admin->setFUserId($userId);
        $tbl_admin->setFStatus($status);
        $tbl_admin->setFCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID));
        $tbl_admin->setFCreatedDatetime($datetime);
        $tbl_admin->setFRole($role);
        $tbl_admin->save();

        $output = array(
            "error" => false
        );
        echo json_encode($output);
        return sfView::HEADER_ONLY;
    }

    public function executeChangePassword()
    {
        if ($this->getRequestParameter('oldPassword')) {
            $c = new Criteria();
            $c->add(TblUserPeer::F_ID, $this->getUser()->getAttribute(Globals::SESSION_USERID));
            $exist = TblUserPeer::doSelectOne($c);

            if ($exist->getFPassword() <> $this->getRequestParameter('oldPassword')) {
                $this->setFlash('errorMsg', "Invalid password");
            } else {
                $exist->setFPassword($this->getRequestParameter('newPassword'));
                $exist->save();
                $this->setFlash('successMsg', "Password updated");
            }
        }
    }

    public function executeFetchRole()
    {
        $c = new Criteria();
        $c->add(AppUserRolePeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $c->addAscendingOrderByColumn(AppUserRolePeer::ROLE_CODE);
        $appUserRoles = AppUserRolePeer::doSelect($c);

        foreach ($appUserRoles as $appUserRole) {
            $arr[] = $appUserRole->getRoleCode();
        }
        echo json_encode($arr);
        return sfView::HEADER_ONLY;
    }

    public function executeUserRole()
    {
        $query = "SELECT userAccess.access_code, userAccess.menu_label, userAccess.parent_id
                    , userAccess.status_code, userAccess.tree_seq, userAccess.tree_level
                FROM app_user_access userAccess
                     WHERE userAccess.status_code = 'active' ORDER BY userAccess.tree_seq";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $rs = $statement->executeQuery();

        $idx = 0;
        $resultArr = array();
        while ($rs->next()) {
            $arr = $rs->getRow();
            $resultArr[$idx] = $arr;
            $idx++;
        }
        $this->resultArr = $resultArr;
    }

    public function executeFetchUserAccessRole()
    {
        $roleId = $this->getRequestParameter('roleId');
        if (!isset($roleId))
            $roleId = 0;

        $userAccessArr = $this->findUserAccessRole($roleId);

        echo json_encode($userAccessArr);

        return sfView::HEADER_ONLY;
    }

    public function executeDoSaveRole()
    {
        $roleId = $this->getRequestParameter('roleId');
        $roleCode = $this->getRequestParameter('roleCode');
        $roleDesc = $this->getRequestParameter('roleDesc');
        $status = $this->getRequestParameter('status');
        $roleCodeSelected = $this->getRequestParameter('roleCodeSelected');

        $roleCodeArr = explode("|||", $roleCodeSelected);

        $c = new Criteria();
        $c->add(AppUserRolePeer::ROLE_CODE, $roleCode);
        if (isset($roleId) && trim($roleId) != '') {
            $c->add(AppUserRolePeer::ROLE_ID, $roleId, Criteria::NOT_EQUAL);
        }

        $exist = AppUserRolePeer::doSelectOne($c);
        if ($exist) {
            $output = array(
                "error" => true,
                "errorMsg" => "Role Code already exist."
            );
            echo json_encode($output);
            return sfView::HEADER_ONLY;
        }

        if (isset($roleId) && trim($roleId) != '') {
            $appUserRole = AppUserRolePeer::retrieveByPk($roleId);
            if (!isset($appUserRole)) {
                $output = array(
                    "error" => true,
                    "errorMsg" => "Serious Problem happen in server."
                );
                echo json_encode($output);
                return sfView::HEADER_ONLY;
            }

            $c = new Criteria();
            $c->add(AppUserRolePeer::ROLE_ID, $roleId);
            $appUserRole = AppUserRolePeer::doSelectOne($c);
            if (!isset($appUserRole)) {
                $output = array(
                    "error" => true,
                    "errorMsg" => "Serious Problem happen in server."
                );
                echo json_encode($output);
                return sfView::HEADER_ONLY;
            }
        } else {
            $appUserRole = new AppUserRole();
            $appUserRole->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID));
        }

        $appUserRole->setRoleCode($roleCode);
        $appUserRole->setRoleDesc($roleDesc);
        $appUserRole->setStatusCode($status);

        $appUserRole->save();

        $query = "DELETE FROM app_user_role_access WHERE role_id =". $roleId;
        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $statement->executeQuery();
        foreach ($roleCodeArr as $accessCode) {
            $app_user_role_access = new AppUserRoleAccess();
            $app_user_role_access->setAccessCode($accessCode);
            $app_user_role_access->setRoleId($roleId);
            $app_user_role_access->save();
        }

        $output = array(
            "error" => false
        );
        echo json_encode($output);
        return sfView::HEADER_ONLY;
    }

    public function executeLogin()
    {
    }

    public function executeDoLogin()
    {
        $existUser = null;
        if (sfConfig::get('sf_environment') == Globals::SF_ENVIRONMENT_DEV) {
            // ******************* uncomment for testing purpose ****************
            $existUser = TblUserPeer::retrieveByPk(-1);
        } else {
            $username = trim($this->getRequestParameter('modlgn_username'));
            $password = trim($this->getRequestParameter('modlgn_passwd'));

            if ($username == '' || $password == '') {
                $this->setFlash('errorMsg', "Invalid username or password.");
                return $this->redirect('admin/login');
            }

            $this->getUser()->getAttributeHolder()->clear();

            /*	    user      	*/
            $c = new Criteria();
            $c->add(TblUserPeer::F_USERNAME, $username);
            $c->add(TblUserPeer::F_PASSWORD, $password);
            $c->add(TblUserPeer::F_TYPE, Globals::USERTYPE_ADMIN);
            $c->add(TblUserPeer::F_STATUS, Globals::STATUS_ACTIVE);
            $existUser = TblUserPeer::doSelectOne($c);
        }


        if ($existUser) {
            $c = new Criteria();
            $c->add(TblAdminPeer::F_USER_ID, $existUser->getFId());
            $existAdmin = TblAdminPeer::doSelectOne($c);

            $this->getUser()->clearCredentials();
            $this->getUser()->setAuthenticated(true);
            $this->getUser()->addCredential($existAdmin->getFRole());
            $this->getUser()->addCredential("dashboard");

            //var_dump($existAdmin->getFRole());

            $c = new Criteria();
            $c->add(AppUserRolePeer::ROLE_CODE, $existAdmin->getFRole());
            $exist = AppUserRolePeer::doSelectOne($c);
            if ($exist) {
                $userAccessArr = $this->findUserAccessRole($exist->getRoleId());
                foreach ($userAccessArr as $userAccess){
                    $this->getUser()->addCredential($userAccess);
                    //var_dump($userAccess);
                }
            }
            //exit();
            $this->getUser()->setAttribute(Globals::SESSION_ADMINID, $existAdmin->getFId());
            $this->getUser()->setAttribute(Globals::SESSION_USERID, $existUser->getFId());
            $this->getUser()->setAttribute(Globals::SESSION_USERNAME, $existUser->getFUsername());
            $this->getUser()->setAttribute(Globals::SESSION_USERTYPE, $existAdmin->getFRole());

            return $this->redirect('admin/dashboard');
        }

        $this->setFlash('errorMsg', "Invalid username or password.");
        return $this->redirect('admin/login');
    }

    public function executeLoginSecurity()
    {
        $this->setFlash('errorMsg', "Login required. This page is not public.");
        return $this->redirect('admin/login');
    }

    public function executeLogout()
    {
        $this->getUser()->clearCredentials();
        $this->getUser()->getAttributeHolder()->clear();
        return $this->redirect('admin/login');
    }

    public function executeUpdateMenuIdx()
    {
        $this->getUser()->setAttribute(Globals::SESSION_ADMIN_MENU_IDX, $this->getRequestParameter('menuIdx'));
        return sfView::HEADER_ONLY;
    }

    // #####################################
    function findUserAccessRole($roleId)
    {
        $query = "SELECT userAccess.access_code, userAccess.menu_label, userAccess.parent_id
                    , userAccess.status_code, userAccess.tree_seq, userAccess.tree_level
                    , roleAccess.role_access_id
                FROM app_user_access userAccess
                        INNER JOIN app_user_role_access roleAccess ON userAccess.access_code = roleAccess.access_code AND roleAccess.role_id = " . $roleId .
                    " WHERE userAccess.status_code = 'active' ORDER BY userAccess.tree_seq";
        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $rs = $statement->executeQuery();

        while ($rs->next()) {
            $arr = $rs->getRow();
            $userAccessArr[] = $arr['access_code'];
        }

        return $userAccessArr;
    }
}
